package rexsee.service;

import rexsee.core.alarm.RexseeAlarm;
import rexsee.core.notification.NotificationArgumentsSheet;
import rexsee.core.utilities.Escape;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class RexseePush {

	public static final String DATABASE_PUSH = "push.db";
	public static final String TABLE_PUSH = "push";
	public static final String TABLE_PUSH_SMS = "push_sms";
	public static final String TABLE_PUSH_HTTP = "push_http";
	public static final String TABLE_PUSH_HTTP_ARGUMENTS = "push_http_arguments";
	public static final String PUSH_TYPE_HTTP = "http";
	public static final String PUSH_TYPE_SMS = "sms";
	public static final String PUSH_TYPE_BROWSER = "browser";
	public static final int PUSH_STATUS_TODO = 0;
	public static final int PUSH_STATUS_DONE = 1;

	public static void initDatabase(Context context) {
		SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_PUSH, Context.MODE_PRIVATE, null);
		db.execSQL("CREATE TABLE if not exists " + TABLE_PUSH + " (id int, date long, type Text, done int, address TEXT, arguments TEXT, Primary key(id));");
		db.execSQL("CREATE TABLE if not exists " + TABLE_PUSH_SMS + " (phoneNumber TEXT);");
		db.execSQL("CREATE TABLE if not exists " + TABLE_PUSH_HTTP + " (url TEXT,userId TEXT, userPassword TEXT, encoding Text);");
		db.execSQL("CREATE TABLE if not exists " + TABLE_PUSH_HTTP_ARGUMENTS + " (duration int,timeout int);");
		db.close();
	}
	public static void add(Context context, String type, long when, String address, String body) {
		if (body == null) return;
		NotificationArgumentsSheet argu = (new NotificationArgumentsSheet()).parseArguments(body);
		int id = argu.getId((int) when);
		try {
			SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_PUSH, Context.MODE_PRIVATE, null);
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_PUSH + " where id=" + id + ";", null);
			if (cursor == null || cursor.getCount() == 0) {
				String sql = "INSERT INTO " + TABLE_PUSH + " VALUES (" + id + "," + when + ", '" + type + "',  " + PUSH_STATUS_TODO + ", '" + address + "', '" + Escape.escape(body) + "');";
				db.execSQL(sql);
				(new RexseeAlarm(context)).set(body);
			} else {
				if (argu.forcerepeat) {
					String sql = "UPDATE " + TABLE_PUSH + " SET date=" + when + ",type='" + type + "',done=" + PUSH_STATUS_TODO + ",address='" + address + "',arguments='" + Escape.escape(body) + "' where id=" + id + ";";
					db.execSQL(sql);
					(new RexseeAlarm(context)).set(body);
				}
			}
			if (cursor != null) cursor.close();
			db.close();
		} catch (Exception e) {
		}
	}

}
